package net.homeip.jcperera.nu.core.utils;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.UUID;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.faces.bean.RequestScoped;
import javax.inject.Named;

import net.homeip.jcperera.nu.core.CoreBase;

/**
 * <p>
 * Session Bean implementation class RandomUtil
 * </p>
 * <p>
 * Handles the Random Numbers and IDs generation both from the EJBs and from the web side (i.e. generating random IDs to
 * use to prevent CSRF or create unique IDs to be used in JS) .
 * </p>
 * 
 * @name RandomUtil Bean class
 * @author julio.c.perera@gmail.com
 * @application nu
 * @since 0.1.0.0
 */

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
@LocalBean
@RequestScoped
@Named(RandomUtil.componentName)
public class RandomUtil extends CoreBase implements Serializable
{
    // Required to implement Serializable interface
    private static final long  serialVersionUID = 64034983317124359L;

    // CoreBase properties, for easy use from other components, as well as logging
    public static final int    runtimeLevel     = 0;
    public static final String moduleName       = "core";
    public static final String componentName    = "nu_core_utils_random_util";

    private String             lastGeneratedID  = null;

    // Get the log
    // private final static Logger log = Logger.getLogger();

    public RandomUtil()
    {
    }

    /**
     * Converts a byte-array to a visual {@link String} representation.
     * 
     * @param byteArray
     *            The byte-array to convert to {@link String}
     * @return The byte-array converted to {@link String}
     */
    public static String toHexString(byte[] byteArray)
    {
        String hex = "";
        for (int i = 0; i < byteArray.length; i++)
            hex += StringUtil.padLeft(Integer.toHexString(byteArray[i] & 0xFF).toLowerCase(), 2, '0');
        return hex;
    }

    /**
     * Generates a random {@link String} that can be used as an identifier. This method attempts to generate somewhat
     * cryptographically secure random numbers, but without a really random number generator there is no guarantee of
     * that. Created for generating IDs to prevent CSRF or link dynamic components via JS.
     */
    public String generateRandomID()
    {
        lastGeneratedID = UUID.randomUUID().toString().replaceAll("-", "");
        try
        {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] randomDigest = sha.digest(new Integer(random.nextInt()).toString().getBytes());
            lastGeneratedID = toHexString(randomDigest);
        }
        catch (Exception e)
        {
        }
        lastGeneratedID = "id".concat(lastGeneratedID);
        return lastGeneratedID;
    }

    /**
     * 
     */
    public String retrieveLastGeneratedID()
    {
        return lastGeneratedID;
    }
}
